<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>轮播图</title>
</head>
<body>

<div class="carousel">
    <!-- 轮播图图片 -->
    <img src="./images/1.png" class="active" alt="Image 1">
    <img src="./images/2.png" alt="Image 2">
    <img src="./images/3.png" alt="Image 3">
    <!-- 导航按钮 -->
    <button class="prev" onclick="changeSlide(-1)">&#10094;</button>
    <button class="next" onclick="changeSlide(1)">&#10095;</button>
</div>
<style>
    /* 设置轮播图容器样式 */
    .carousel {
        width: 80%;
        margin: 20px auto;
        position: relative;
        overflow: hidden;
    }
    /* 设置轮播图图片样式 */
    .carousel img {
        width: 100%;
        display: none;
        transition: opacity 1s ease-in-out;
    }
    /* 设置当前显示的图片样式 */
    .carousel img.active {
        display: block;
        opacity: 1;
    }
    /* 设置导航按钮样式 */
    .carousel .prev, .carousel .next {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        background-color: rgba(0, 0, 0, 0.5);
        color: white;
        border: none;
        padding: 10px;
        cursor: pointer;
    }
    /* 设置上一个按钮样式 */
    .carousel .prev {
        left: 10px;
    }
    /* 设置下一个按钮样式 */
    .carousel .next {
        right: 10px;
    }
</style>
<script>
// 当前显示的图片索引
let currentSlide = 0;
// 获取所有轮播图图片
const slides = document.querySelectorAll('.carousel img');
// 改变图片
function changeSlide(step) {
    // 隐藏当前图片
    slides[currentSlide].classList.remove('active');
    // 更新当前图片索引
    currentSlide += step;
    // 如果索引超出范围，重置为0或最后一张图片
    if (currentSlide >= slides.length) {
        currentSlide = 0;
    } else if (currentSlide < 0) {
        currentSlide = slides.length - 1;
    }
    // 显示新的图片
    slides[currentSlide].classList.add('active');
}

// 自动播放轮播图，每1秒切换一次
setInterval(() => {
    changeSlide(1);
}, 1000);
</script>

</body>
</html>